package com.btashov.linkedlist;

import com.btashov.datastructure.LinkedListNode;
import com.btashov.datastructure.Node;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;


/**
 * todo: 2.1 to remove duplicates from an unsorted linked list.
 * <p/>
 * FOLLOW UP
 * How would you solve this problem if a temporary buffer is not allowed?
 */
public class Duplicate {

    public static LinkedListNode removeDuplicateNonStandardList(LinkedListNode list) {
        if (list == null || list.getHead() == null) {
            throw new IllegalArgumentException("Invalid List");
        }

        Set<Integer> set = new HashSet<Integer>();
        Node prev = list.getHead();
        Node current = list.getHead().getNext();
        set.add(prev.getId());
        while (current != null) {
            if (!set.contains(current.getId())) {
                set.add(current.getId());
                prev.setNext(current);
                prev = current;
            }
            current = current.getNext();
        }
        prev.setNext(null);
        return list;
    }

    //standard
    public static LinkedList removeDuplicateTyped(LinkedList list) {
        return new LinkedList(new HashSet(list));
    }

    public static LinkedList<Node> removeDuplicate(LinkedList<Node> list) {
        return new LinkedList<Node>(new HashSet<Node>(list));
    }


    /**
     * redundant {@code for} each cycle, because of Set buffer in java
     *
     * @param list
     * @return
     * @see Set
     */
    public static LinkedList<Node> removeDuplicateStandard(LinkedList<Node> list) {
        if (list == null || list.getFirst() == null) {
            throw new IllegalArgumentException("Invalid List");
        }

        Set<Node> set = new HashSet<Node>();
        for (Node node : list) {
            set.add(node);
        }

        return new LinkedList<Node>(set);
    }

    /**
     * redundant {@code for} cycle, because of Set buffer in java
     *
     * @param list
     * @return
     * @see Set
     */
    public static LinkedList<Node> removeDuplicateStandardOldStyle(LinkedList<Node> list) {
        if (list == null || list.getFirst() == null) {
            throw new IllegalArgumentException("Invalid List");
        }

        Set<Node> set = new HashSet<Node>();
        for (int index = 0; index < list.size(); index++) {
            set.add(list.get(index));
        }

        return new LinkedList<Node>(set);
    }
}



